<template>
  <div class="dynamic-property-editor space-y-6 p-4 bg-white rounded-lg shadow-sm">
    <!-- 组件基础信息 -->
    <div class="border-b pb-3">
      <h3 class="text-lg font-semibold">{{ componentConfig.displayName }}</h3>
      <p class="text-sm text-gray-500">{{ componentConfig.description }}</p>
    </div>

    <!-- 配置面板 -->
    <div v-for="(panel, panelIndex) in componentConfig.configSchema" :key="panelIndex">
      <h4 class="text-sm font-medium text-gray-700 mb-3">{{ panel.title }}</h4>
      <div class="grid grid-cols-1 gap-4">

        <!-- 动态生成字段控件 -->
        <div v-for="(field, fieldIndex) in panel.fields" :key="fieldIndex" class="space-y-2">
          <label class="text-xs text-gray-500">{{ field.label }}</label>
          <!-- 颜色选择器 -->
          <input v-if="field.controlType === 'color-editor'" type="color" v-model="componentProps[field.name]"
            @change="handlePropChange(field.name)" class="w-full h-10 p-0 border border-gray-200 rounded-md">

          <!-- 下拉选择器 -->
          <select v-else-if="field.controlType === 'enum-editor'" v-model="componentProps[field.name]"
            @change="handlePropChange(field.name)"
            class="w-full px-3 py-2 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
            <option v-for="option in field.options" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>

          
          <!-- 数字输入 -->
          <input v-else-if="field.controlType === 'number-editor'" type="number"
            v-model.number="componentProps[field.name]" @change="handlePropChange(field.name)" :min="field.min"
            :max="field.max"
            class="w-full px-3 py-2 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          <!-- 开关 -->
          <boolean-editor v-else-if="field.controlType === 'boolean-editor'" :value="componentProps[field.name]" @input="handlePropChange(field.name)"></boolean-editor>
          <array-display v-else-if="field.controlType === 'array-editor'" :value="componentProps[field.name]" @edit="handleJsonEdit(field.name, 'array')"></array-display>
          <object-display v-else-if="field.controlType === 'object-editor'" :value="componentProps[field.name]" @edit="handleJsonEdit(field.name, 'object')"></object-display>
          <!-- 图片选择器 -->
          <image-editor v-else-if="field.controlType === 'image-editor'" :value="componentProps[field.name]" @input="handleImageChange(field.name, $event)"></image-editor>
          <!-- 默认文本输入 -->
          <input v-else-if="field.controlType === 'string-editor'" type="text" v-model="componentProps[field.name]"
            @change="handlePropChange(field.name)"
            class="w-full px-3 py-2 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
        </div>
      </div>
    </div>

    <!-- 事件绑定 -->
    <div v-if="componentConfig.events.length">
      <h4 class="text-sm font-medium text-gray-700 mb-3">事件绑定</h4>
      <div class="space-y-3">
        <div v-for="(event, index) in componentConfig.events" :key="index">
          <label class="text-xs text-gray-500 block mb-1">{{ event.label }}</label>
          <select v-model="eventBindings[event.name]" @change="handleEventBindingChange(event.name)"
            class="w-full px-3 py-2 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
            <option value="">请选择动作</option>
            <option value="navigate">页面跳转</option>
            <option value="showToast">显示提示</option>
            <option value="customCode">自定义代码</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 第三方JSON编辑器弹窗组件 -->
    <json-editor 
      v-model:is-open="isJsonModalOpen" 
      v-model:is-child-modal-open="isChildModalOpen" 
      :value="editingJsonValue" 
      @confirm="handleJsonConfirm"
      @close="handleJsonClose"
    />
  </div>
</template>

<script>
import { ref, watch } from 'vue';
import ArrayDisplay from '../editors/ArrayDisplay.vue';
import ObjectDisplay from '../editors/ObjectDisplay.vue';
import BooleanEditor from '../editors/BooleanEditor.vue';
import JsonEditor from '../editors/JsonEditor.vue';
import ImageEditor from '../editors/ImageEditor.vue';

export default {
  props: {
    // 组件配置（由ComponentRegistrar解析后的配置）
    componentConfig: {
      type: Object,
      required: true
    },
    // 组件当前属性值
    componentProps: {
      type: Object,
      required: true
    },
    // 事件绑定配置
    eventBindings: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    BooleanEditor,
    ArrayDisplay,
    ObjectDisplay,
    JsonEditor,
    ImageEditor
  },
  emits: ['update:componentProps', 'update:eventBindings'],
  setup(props, { emit }) {
    // 响应式处理组件属性
    const localProps = ref({ ...props.componentProps });
    const localEventBindings = ref({ ...props.eventBindings });
    
    // 弹窗状态
    const isJsonModalOpen = ref(false);
    const isChildModalOpen = ref(false);
    
    // 正在编辑的字段信息
    const editingFieldName = ref('');
    const editingJsonValue = ref(null);
    const editingFieldType = ref(''); // 'array' 或 'object'
    
    // 监听外部属性变化，同步到本地
    watch(() => props.componentProps, (newVal) => {
      localProps.value = { ...newVal };
    }, { deep: true });

    watch(() => props.eventBindings, (newVal) => {
      localEventBindings.value = { ...newVal };
    }, { deep: true });
    
    // JSON编辑处理
    const handleJsonEdit = (fieldName, fieldType) => {
      editingFieldName.value = fieldName;
      editingFieldType.value = fieldType;
      // 根据字段类型初始化默认值
      const defaultValue = fieldType === 'array' ? [] : {};
      editingJsonValue.value = JSON.parse(JSON.stringify(props.componentProps[fieldName] || defaultValue));
      isJsonModalOpen.value = true;
    };
    
    // JSON确认处理
    const handleJsonConfirm = (newValue) => {
      localProps.value[editingFieldName.value] = newValue;
      emit('update:componentProps', { ...localProps.value });
      isJsonModalOpen.value = false;
    };
    
    // JSON关闭处理
    const handleJsonClose = () => {
      isJsonModalOpen.value = false;
    };
    const handleImageChange = (propName, value) => {
      localProps.value[propName] = value;
      emit('update:componentProps', { ...localProps.value });
    };
    // 属性变化处理
    const handlePropChange = (propName) => {
      emit('update:componentProps', { ...localProps.value });
    };

    // 事件绑定变化处理
    const handleEventBindingChange = (eventName) => {
      emit('update:eventBindings', { ...localEventBindings.value });
    };

    return {
      localProps,
      localEventBindings,
      isJsonModalOpen,
      isChildModalOpen,
      editingFieldName,
      editingJsonValue,
      editingFieldType,
      handlePropChange,
      handleImageChange,
      handleEventBindingChange,
      handleJsonEdit,
      handleJsonConfirm,
      handleJsonClose
    };
  }
};
</script>

<style scoped>
.dynamic-property-editor {
  font-size: 14px;
}

/* 表单控件样式 */
input:focus,
select:focus {
  transition: all 0.2s ease;
}

/* 开关样式优化 */
.switch-label {
  user-select: none;
}
</style>